//
//  OauthViewController.swift
//  SinaWeibo
//
//  Created by mac on 15/12/14.
//  Copyright © 2015年 cn.bboy-Deven. All rights reserved.
//

import UIKit
//import AFNetworking
import AFNetworking
import SVProgressHUD
class OauthViewController: UIViewController  {
    
    let webView = UIWebView()
    override func viewDidLoad() {
        super.viewDidLoad()
        // 调用 -- 设置 Oauthview 的 导航按钮
        setNavigationItem()
        // 调用 -- 设置 webView 的初始展示界面
        loadOauthView()
    }

    override func loadView() {
        view = webView
        // 设置 webview 代理
        webView.delegate = self
    }
    
    // 设置 Oauthview 的 导航按钮
    private func setNavigationItem (){
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "setDefaultInfo")
    }
    
    // 点击关闭 回到 原控制器
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    // 设置 默认账户信息
    @objc private func setDefaultInfo(){
    
        let jsString = "document.getElementById('userId').value = '18353367035' ,document.getElementById('passwd').value = 'iamsorrytoyou!'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
   
    
    // 设置 webview 初始展示界面
     func loadOauthView(){
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        webView.loadRequest(NSURLRequest(URL: url!))
    
    }
    
}
//    // 让 OauthViewController 有 webView 的代理
    extension OauthViewController: UIWebViewDelegate  {
        func webViewDidStartLoad(webView: UIWebView) {
            SVProgressHUD.show()
        }
        func webViewDidFinishLoad(webView: UIWebView) {
            SVProgressHUD.dismiss()
        }
        
        func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
           //let urlString = request.URL?.absoluteString
            //print(urlString)
            
            // 屏蔽 一些请求, 限制用户操作
            guard let urlString = request.URL?.absoluteString else {
                // 如果 请求 url 为空, 返回错误
                return false
            }
            if urlString.hasPrefix("https://api.weibo.com/") {
                // 希望加载
                return true
            }
            if !urlString.hasPrefix("http://www.baidu.com") {
//                一定不是请求成功后的回调  同样也不会是 我们希望加载的页面
                return false
            }
            let query = request.URL?.query
            if let q = query {
                let codestr = "code="
                let Code = q.substringFromIndex(codestr.endIndex)
                // 这里 得到 返回的 网页授权码
                print(Code)
                getAccessToken(Code)
            }
            return true
        }
        
        // 回调
        private func getAccessToken(code :String ) {
            UserAccountViewModel().getAccessToken(code) { (isSuccess) -> () in
                if isSuccess {
                    print("登陆成功")
                    self.close()
                }else {
                    print("登录失败")
                }
            }
        
        }
        
        
}



